package com.sun.service.impl;

import com.sun.dao.BlogDao;
import com.sun.dao.TagDao;
import com.sun.dto.SearchBlog;
import com.sun.dto.TagBlog;
import com.sun.pojo.Blog;
import com.sun.service.BlogService;
import com.sun.util.MarkdownUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static java.lang.Long.parseLong;

/**
 * @author: glorysun
 * @date: 2020/8/5
 */
@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogDao blogDao;

    @Autowired
    private TagDao tagDao;

    @Override
    public Blog selectBlogById(Long id) {
        return blogDao.selectBlogById(id);
    }

    @Override
    @Transactional
    public Blog selectBlogByIdAndMarkdownTOHTML(Long id) {
        Blog blog=blogDao.selectBlogById(id);
        String context=blog.getContent();
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(context));
        return blog;
    }

    @Override
    public List<Blog> selectBlogList() {
        return blogDao.selectBlogList();
    }

    @Override
    public int insertBlog(Blog blog) {
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blog.setViews(0);
        saveTags(blog);
        return blogDao.insertBlog(blog);
    }

    public void saveTags(Blog blog){
        String tagIds=blog.getTagIds();
        String[] tags=tagIds.split(",");
        List<String> tagList= Arrays.asList(tags);
        for(String tl:tagList){
            TagBlog tagBlog=new TagBlog(parseLong(tl) ,blog.getId());
            blogDao.insertTagBlog(tagBlog);
        }
    }
    @Override
    public int updateBlog(Blog blog) {
        blog.setUpdateTime(new Date());
        //删除标签博客表中的相关信息
        tagDao.deleteTagByBlogId(blog.getId());
        saveTags(blog);
        return blogDao.updateBlog(blog);
    }

    @Override
    public int deleteBlog(Long id) {
        blogDao.deleteTagBlog(id);
        return blogDao.deleteBlog(id);
    }

    @Override
    public List<Blog> selectBlogByCondition(SearchBlog searchBlog) {
        return blogDao.selectBlogByCondition(searchBlog);
    }

    @Override
    public List<Blog> selectBlogByType(Long id) {
        return blogDao.selectBlogByType(id);
    }

    @Override
    public List<Blog> selectBlogByTag(Long id) {
        return blogDao.selectBlogByTag(id);
    }

    @Override
    public List<Blog> selectBlogByTitle(String title) {
        return blogDao.selectBlogByTitle(title);
    }

    @Override
    public List<Blog> selectBlogListTen() {
        return blogDao.selectBlogListTen();
    }

    @Override
    public List<Blog> selectBlogListByComment() {
        return blogDao.selectBlogListByComment();
    }
}
